﻿// =====================================================================
//
//  This file is part of the Microsoft Dynamics CRM SDK code samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//
// =====================================================================

using System;
using System.Security.Principal;

namespace SL.IdentityModel.Claims
{
	/// <summary>
	/// This class implements IClaimsPrincipal, and represents a claims based security principal
	/// </summary>
	public class ClaimsPrincipal : IClaimsPrincipal, IPrincipal
	{
		private IClaimsIdentity _identity;

		/// <summary>
		/// Creates an instance of a ClaimsPrincipal object
		/// </summary>
		/// <param name="identity">sets .Identity and .ClaimsIdentity</param>
		public ClaimsPrincipal(IClaimsIdentity identity)
		{
			_identity = identity;
		}

		#region IClaimsPrincipal

		/// <summary>
		/// This references the same IClaimsIdentity instance as the Identity field
		/// </summary>
		public IClaimsIdentity ClaimsIdentity
		{
			get { return _identity; }
		}

		#endregion

		#region IPrincipal

		public IIdentity Identity
		{
			get { return _identity; }
		}

		public bool IsInRole(string role)
		{
			if ((_identity.Claims != null) && (null != _identity.RoleClaimType))
			{
				foreach (Claim claim in _identity.Claims)
				{
					if (StringComparer.Ordinal.Equals(claim.ClaimType, _identity.RoleClaimType) && StringComparer.Ordinal.Equals(claim.Value, role))
					{
						return true;
					}
				}
			}
			return false;
		}

		#endregion
	}
}
